import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
// 创建实例时配置默认值
const axiosInstance = axios.create({
  baseURL: 'http://api_devs.wanxikeji.cn',
  tiemout: 5000
})
axiosInstance.interceptors.response.use(
  (res) => {
    if (res.data.code !== 2000) {
      if (res.data.code === 3000) {
        localStorage.removeItem('token')
        router.push('/login')
      }
      console.log('后端返回异常')
      return Promise.reject(new Error('1111'))
    } else {
      return res
    }
  },
  (e) => {
    console.log(e)
    if (e.request.status === 404) {
      console.log(e.request.status)
    }
  }
)
axiosInstance.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    return response
  },
  (error) => {
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)
const jsonHttpcode = {
  200: '数据请求成功',
  301: '资源已被重定向',
  400: '请求参数错误',
  401: '未授权',
  403: '拒绝访问',
  404: '资源不存在',
  405: '请求方法不允许',
  406: '不接受',
  408: '请求超时',
  410: '资源不存在',
  500: '服务器错误',
  502: '网关错误',
  503: '服务不可用',
  504: '网关超时'
}

function axiosApi(url, method, data, fn) {
  axiosInstance({
    url: url,
    method: method,
    data: data
  }).then((jsonresult) => {
    console.log(jsonresult)
    if (jsonresult) {
      ElMessage({
        type: 'success',
        message: jsonHttpcode[jsonresult.status]
      })
      fn(jsonresult.data)
    } else {
      ElMessage({
        type: 'error',
        message: jsonHttpcode[jsonresult.status]
      })
    }
  })
}
export default axiosApi
